package com.wangsh.usersCenter.web.head.controller;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wangsh.usersCenter.common.controller.BaseController;
import com.wangsh.usersCenter.common.pojo.ApiResponse;
import com.wangsh.usersCenter.common.pojo.ApiResponseEnum;
import com.wangsh.usersCenter.common.util.ConstatFinalUtil;
import com.wangsh.usersCenter.users.pojo.AUsers;
import com.wangsh.usersCenter.users.service.INoLoginOperService;
import com.wangsh.usersCenter.users.service.IUsersDbService;

/**
 * 	不需要登陆的Controller
 * 	@author wangsh
 */
@Controller
public class NoLoginHeadController extends BaseController
{
	@Resource
	private IUsersDbService usersDbService;
	@Resource
	private INoLoginOperService noLoginOperService;
	
	/**
	 * 打开登陆页面
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("--login--");
		AUsers users = (AUsers) this.findObjfromSession(request, "users");
		if(users != null)
		{
			String returnUrl = request.getParameter("returnUrl");
			
			if(this.loginSuccedReturnUrl(response, returnUrl, users))
			{
				return null ; 
			}
			/* 登陆成功 */
			return "redirect:/head/users/main.htm" ; 
		}
		return "/head/login";
	}
	
	/**
	 * 登陆提交操作
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/loginSubmit")
	public String loginSubmit(HttpServletRequest request,HttpSession session , HttpServletResponse response,Model model) throws IOException
	{
		ConstatFinalUtil.SYS_LOGGER.info("--loginSubmit--");
		
		/* 获取请求头 */
//		Enumeration<String> headerEnu = request.getHeaderNames();
//		while(headerEnu.hasMoreElements())
//		{
//			String key = headerEnu.nextElement();
//			String val = request.getHeader(key);
//			ConstatFinalUtil.SYS_LOGGER.info("{}==请求头=={}",key,val);
//		}
		
		ApiResponse<Object> apiResponse = new ApiResponse<Object>() ; 
		/* 接收参数 */
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String code = request.getParameter("code");
		
		String returnUrl = request.getParameter("returnUrl");
		String randSess = (String) session.getAttribute("randSess");
		Integer failedCount = (Integer) session.getAttribute("failedCount");
		if(failedCount == null)
		{
			failedCount = 0 ; 
		}
		
		/* 移除验证码,防止重复使用 */
		session.removeAttribute("randSess");
		
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("email", email);
		paramsMap.put("password", password);
		paramsMap.put("code", code);
		paramsMap.put("randSess", randSess);
		paramsMap.put("failedCount", failedCount);
		/* 调用Service方法 */
		apiResponse = this.noLoginOperService.operLoginSubmitService(paramsMap);
		if(ApiResponseEnum.STATUS_SUCCESS.getStatus() == apiResponse.getCode() )
		{
			Map<String, Object> dataMapJava = apiResponse.getDataMapJava() ; 
			/* 登陆成功 */
			AUsers users = (AUsers) dataMapJava.get("users");
			Date lastLoginTime = (Date) dataMapJava.get("lastLoginTime");
			
			session.setAttribute("users", users);
			session.setAttribute("lastLoginTime", lastLoginTime);
			
			if(this.loginSuccedReturnUrl(response, returnUrl, users))
			{
				return null ; 
			}
			/* 登陆成功 */
			return "redirect:/head/users/main.htm" ; 
		}else if(ApiResponseEnum.INFO_PASS_INCORRECT.getStatus() == apiResponse.getCode())
		{
			/* 密码输错次数+1 */
			session.setAttribute("failedCount", failedCount + 1);
		}
		
		Map<String, Object> dataMapJava = apiResponse.getDataMapJava() ; 
		model.addAttribute("users", dataMapJava.get("users"));
		
		/* 提示信息 */
		model.addAttribute("response", apiResponse.toJSON());
		return this.login(request,response);
	}
	
	/**
	 * 打开注册页面
	 * @return
	 */
	@RequestMapping("/register")
	public String register()
	{
		ConstatFinalUtil.SYS_LOGGER.info("--register--");
		return "/head/register";
	}
	
	/**
	 * 注册提交操作
	 * @return
	 */
	@RequestMapping("/registerSubmit")
	public String registerSubmit(HttpServletRequest request,HttpSession session , Model model)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>() ; 
		ConstatFinalUtil.SYS_LOGGER.info("--registerSubmit--");
		
		/* 接收参数 */
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String code = request.getParameter("code");
		String randSess = (String) session.getAttribute("randSess");
		
		/* 移除验证码,防止重复使用 */
		session.removeAttribute("randSess");
		
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("email", email);
		paramsMap.put("password", password);
		paramsMap.put("code", code);
		paramsMap.put("randSess", randSess);
		/* 调用Service方法 */
		apiResponse = this.noLoginOperService.operRegisterSubmitService(paramsMap);
		if(ApiResponseEnum.STATUS_SUCCESS.getStatus() == apiResponse.getCode() )
		{
			/* 注册成功,发送邮件 */
			this.emailVerfySend(request);
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(ApiResponseEnum.INFO_REGISTER_SUCCESS.getStatus() + ""), Collections.EMPTY_MAP);
		}
		
		/* 提示信息 */
		model.addAttribute("response", apiResponse.toJSON());
		return this.register();
	}
	
	/**
	 * 邮箱验证重新发送邮件
	 * @return
	 */
	@RequestMapping("/emailVerfySend")
	public String emailVerfySend(HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--emailVerfySend--");
		HttpSession session = request.getSession();
		ApiResponse<Object> apiResponse = new ApiResponse<Object>() ;
		
		/* 根据邮箱来操作 */
		String email = request.getParameter("email");
		
		/* 移除验证码,防止重复使用 */
		session.removeAttribute("randSess");
		
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("email", email);
		/* 调用Service方法 */
		apiResponse = this.noLoginOperService.operEmailVerfySendService(paramsMap);
		
		session.setAttribute("response", apiResponse.toJSON());
		return "redirect:/common/info.htm" ; 
	}
	
	/**
	 * 验证邮箱
	 * @param request
	 * @return
	 */
	@RequestMapping("/emailVerfy")
	public String emailVerfy(HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--emailVerfy--");
		HttpSession session = request.getSession() ;
		ApiResponse<Object> apiResponse = new ApiResponse<Object>() ;
		
		String email = request.getParameter("email");
		String code = request.getParameter("code");
		if(email == null)
		{
			email = "" ; 
		}
		
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("email", email);
		paramsMap.put("code", code);
		/* 调用Service方法 */
		apiResponse = this.noLoginOperService.operEmailVerfyService(paramsMap);
		
		session.setAttribute("response", apiResponse.toJSON());
		return "redirect:/common/info.htm" ; 
	}
	
	/**
	 * 忘记密码
	 * @return
	 */
	@RequestMapping("/forgetPass")
	public String forgetPass(HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--forgetPass--");
		return "/head/forgetPass" ; 
	}
	
	/**
	 * 忘记密码提交
	 * @return
	 */
	@RequestMapping("/forgetPassSubmit")
	public String forgetPassSubmit(HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--forgetPass--");
		HttpSession session = request.getSession() ;
		ApiResponse<Object> apiResponse = new ApiResponse<Object>() ;
		
		String randSess = session.getAttribute("randSess") + "";
		String email = request.getParameter("email");
		String code = request.getParameter("code");
		if(email == null)
		{
			email = "" ; 
		}
		
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("email", email);
		paramsMap.put("code", code);
		paramsMap.put("randSess", randSess);
		paramsMap.put("contextPath", request.getContextPath());
		/* 调用Service方法 */
		apiResponse = this.noLoginOperService.operForgetPassSubmit(paramsMap);
		
		session.setAttribute("response", apiResponse.toJSON());
		return this.forgetPass(request) ; 
	}
	
	/**
	 * 重置密码
	 * @return
	 */
	@RequestMapping("/resetPass")
	public String resetPass(HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--resetPass--");
		HttpSession session = request.getSession() ;
		ApiResponse<Object> apiResponse = new ApiResponse<Object>() ;
		
		String email = request.getParameter("email");
		String code = request.getParameter("code");
		if(email == null)
		{
			email = "" ; 
		}
		
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("email", email);
		paramsMap.put("code", code);
		/* 调用Service方法 */
		apiResponse = this.noLoginOperService.operResetPass(paramsMap);
		if(apiResponse.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus())
		{
			/* 匹配成功 */
			//符合要求,跳转页面
			return "/head/resetPass" ;
		}
		/* 存储结果 */
		session.setAttribute("response", apiResponse.toJSON());
		return "redirect:/common/info.htm" ; 
	}
	
	/**
	 * 重置密码提交
	 * @return
	 */
	@RequestMapping("/resetPassSubmit")
	public String resetPassSubmit(HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--resetPassSubmit--");
		HttpSession session = request.getSession();
		ApiResponse<Object> apiResponse = new ApiResponse<Object>() ;
		String randSess = session.getAttribute("randSess") + "";
		/* 根据邮箱来操作 */
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String code = request.getParameter("code");
		if(email == null)
		{
			email = "" ; 
		}
		
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("email", email);
		paramsMap.put("password", password);
		paramsMap.put("code", code);
		paramsMap.put("randSess", randSess);
		/* 调用Service方法 */
		apiResponse = this.noLoginOperService.operResetPassSubmit(paramsMap);
		/* 存储结果 */
		session.setAttribute("response", apiResponse.toJSON());
		return "redirect:/common/info.htm" ; 
	}
	
	/**
	 * 单点登陆,returnUrl处理
	 * @param response
	 * @param returnUrl
	 * @param users
	 * @return
	 * @throws IOException
	 */
	private boolean loginSuccedReturnUrl(HttpServletResponse response, String returnUrl, AUsers users) throws IOException
	{
		if(returnUrl == null)
		{
			returnUrl = ""; 
		}
		
		/* 不管如何都要增加Token */
		this.noLoginOperService.operAddUsersTokenService(users);
		String token = users.getTokenStr() ; 
		
		if(!"".equalsIgnoreCase(returnUrl))
		{
			/* 为ReturnUrl带上一个Token:
			 * 令牌:唯一标识 
			 * 原来的returnUrl:http://www.baidu.com
			 * http://www.baidu.com?token=uuid
			 * 
			 * 原来的returnUrl:http://www.baidu.com?id=10
			 * http://www.baidu.com?id=10&a=20&token=uuid
			 * */
			/* token的验证字符串 */
			String tokenStr = "token=" + token ; 
			if(returnUrl.indexOf("&") == -1 && returnUrl.indexOf("?") == -1)
			{
				/* 找到?,并且找到ticket */
				returnUrl += "?" + tokenStr ;
			}else
			{
				returnUrl += "&" + tokenStr ;
			}
			/* 客户端跳转 */
			response.sendRedirect(returnUrl);
			return true ;
		}
		return false ; 
	}
}
